<template>
  <div class="app-container">
    <el-card>
      <h2>AI 聊天助手</h2>
      <el-form @submit.native.prevent>
        <el-form-item label="请输入你的问题：">
          <el-input
            v-model="question"
            placeholder="例如：你是谁？"
            clearable
            style="width: 80%"
          />
          <el-button
            type="primary"
            icon="el-icon-s-promotion"
            style="margin-left: 10px"
            @click="handleChat"
            :loading="loading"
          >发送</el-button>
        </el-form-item>
      </el-form>

      <div v-if="answer" style="margin-top: 20px">
        <el-alert
          title="AI 的回答"
          :description="answer"
          type="success"
          show-icon
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { chatWithAI } from '@/api/ai'

export default {
  name: 'AIChat',
  data() {
    return {
      question: '',
      answer: '',
      loading: false
    }
  },
  methods: {
    handleChat() {
      if (!this.question.trim()) {
        this.$message.warning('请输入问题后再发送。')
        return
      }
      this.loading = true
      chatWithAI(this.question)
        .then(res => {
          if (res.success) {
            this.answer = res.data.answer
          } else {
            this.answer = 'AI回答失败：' + (res.error || '未知错误')
          }
        })
        .catch(err => {
          this.answer = '请求失败：' + (err.message || '未知错误')
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style scoped>
.app-container {
  max-width: 800px;
  margin: 0 auto;
  padding-top: 40px;
}
</style>
